/*
 * @Author: huangyq
 * @Date: 2022-04-26 16:02:41
 * @LastEditTime: 2022-05-19 10:42:49
 * @LastEditors: huangyq
 * @Description: table hook
 * @FilePath: /haotian-operation-manage-system-pc-client/src/hooks/useTable.ts
 */

import { ref, toRaw, isReactive } from 'vue'
import { IBaseRequest, IBaseResponse } from '@/plugins/httpHelper/index'
import { AxiosPromise } from 'axios'

type paramType = Record<string, string | number | undefined>

export function useTable(
  fetch: (params: IBaseRequest) => AxiosPromise<IBaseResponse>
) {
  const list = ref<any[]>([])
  const loading = ref(false)
  let cacheParams: paramType = {}

  /**
   * 查询数据
   */
  async function onTableSearch(
    params?: paramType,
    alias?: Record<string, string>
  ) {
    loading.value = true
    if (params) cacheParams = isReactive(params) ? toRaw(params) : params
    const res: any = await fetch({
      ...cacheParams
    })
    loading.value = false
    if (res.data.success) {
      const aliasData = alias?.data ? alias.data : 'data'
      list.value = res.data[aliasData]
    } else {
      list.value = []
    }
  }

  /**
   * 计算高度
   */
  const countHeight = ref(true)
  function onCountHeight() {
    countHeight.value = !countHeight.value
  }

  return {
    list,
    onTableSearch,
    loading,
    countHeight,
    onCountHeight
  }
}
